﻿#region

using Jiubang.Communication.Server;

#endregion

namespace Jiubang.Communication.Common{
    public abstract class AbstractConverter<T> : IConverter<T>{
        protected static BufferManager bufferManager = BufferManager.Instance;

        #region IConverter<T> Members

        public abstract byte[] Serialize(byte[] buffer, ref int offset, T graph);

        public abstract T Deserialize(byte[] data, ref int offset);

        #endregion

        /// <summary>
        /// 获取一个足够大的缓冲区，实际分配的缓冲区大于等于期望容量
        /// </summary>
        /// <param name="buffer">已分配的缓冲区</param>
        /// <param name="expectedLen">期望缓冲区大小</param>
        /// <returns></returns>
        protected byte[] EnsureBufferSize(byte[] buffer, int expectedLen){
            if (buffer == null) return GetBuffer(expectedLen);
            if (buffer.Length < expectedLen){
                byte[] dest = GetBuffer(expectedLen);
                buffer.CopyTo(dest, 0);
                if (bufferManager.indentedBuffer != null) bufferManager.FreeBuffer(buffer, false);
                return dest;
            }
            return buffer;
        }

        public void FreeBuffer(byte[] data){
            if (bufferManager != null) bufferManager.FreeBuffer(data, false);
        }

        /// <summary>
        /// 如果是前台操作，BufferManager不会初始化，则直接创建一个新数组。
        /// </summary>
        /// <param name="expectedLen"></param>
        /// <returns></returns>
        private static byte[] GetBuffer(int expectedLen){
            if (bufferManager.indentedBuffer == null)
                return new byte[expectedLen];
            return bufferManager.GetBuffer(expectedLen).array;
        }
    }
}